#!/bin/bash
source package_utils.sh

:<<EOF
#测试
# ./package_app.sh h5Test prod acc 2 1.5.0 22 wininner,h5test false hoc false 33
# ./package_app.sh 7lucky prod acc 2 1.0.0 1 7lucky,7lucky false hoc false 11
# ./package_app.sh 18bet prod acc 2 1.0.1 2 18bet,18bet false hoc false 2
# ./package_app.sh 1Winbet prod acc 4 1.2.2 2 1Winbet,1Winbet false hoc false 22

入参说明:
$1:[必选] 打包平台, 如: ios/all/android[其他非空字符,不区分大小写];ios-只打iOS包,all-同时打iOS和Android包,其他非空字符只打Android包
$2:[可选] 打包环境, 如: dev-测试环境,pro-生产环境
$3:[可选] App类型, 如: im/ac, 默认ac
$4:[可选] sysId, 如: 1-默认ac站点
$5:[可选] 版本号, 如: 1.0.1
$6:[可选] 编译版本号, 如: 10
$7:[可选] App名称, 默认ac中英文名称
$8:[可选] 是否打开内部调试工具, 默认不打开
$9:[可选] packageMethod, 打包环境 hoc-测试包(默认)，dist-App Store或Google Play包
$10:[可选] isShellApp, 是否是A面分支(壳App), 默认为false
$11:[可选] groupId, 默认为76
$12:[可选] flutterVersion, flutterSDK版本，2.0-2.5.3， 3.0-3.7.12
$13:[可选] fileName, 默认为空，ipa/apk文件名
$14:[可选] agentId, 默认为空
$15:[可选] domain, 指定使用服务器域名
$16:[可选] branch, 分支
$17:[可选] packageRes, 资源包路径<icon及启动图>
EOF

# 打包计时
SECONDS=0
cur_date=$(date +"%Y%m%d%H%M%S")

# 参数初始化
platform=$1               # 平台
env=$2                    # 服务器环境
appType=$3                # App类型，im或ac
sysId=$4                  # sysId
version=$5                # 版本号
buildCode=$6              # 编译版本号
appNames=$7               # 18bet,18bet【中文App名,英文App名】
openInnerTools=$8         # 是否打开内部工具
packageMethod=$9          # 打包环境 hoc-测试包(默认)，dist-Google Play包
isShellApp=${10}          # 是否是A面分支(壳App)
groupId=${11}             # 分组id
fileName=${13}            # apk文件名
agentId=${14}             # 代理id
targetDomain=${15}        # 指定落地域名
branch=${16}              # 分支
packageRes=${17}          # 资源包路径<icon及启动图>

# 固定配置
showAppType="im"
androidMethod='1'         # 1-默认模式, 3-Google Play包
isAcApp='true'            # true-ac工程包

# 参数默认值处理
[[ -z $openInnerTools || $openInnerTools != "false" && $openInnerTools != "true" ]] && openInnerTools="false"
[[ -z $packageMethod ]] && packageMethod="hoc"
[[ -z $appNames ]] && appNames="18bet,18bet"
[[ -z $isShellApp ]] && isShellApp=false
[[ -z $groupId ]] && groupId="76"

# 处理Google Play包
if [[ $packageMethod = "dist" ]]; then
    openInnerTools="false"
    androidMethod='3'
fi

# 解析App名称
IFS=','
names=($appNames)
IFS=' '
appNameCn=${names[0]}
appNameEn=${names[1]}
appName=${names[1]}

echo "-------- 脚本版本:V0.0.1 --------"
echo "appNames=${appNames}, appName=$appName, appNameEn=$appNameEn, appNameCn=$appNameCn"
echo "openInnerTools=$openInnerTools, androidMethod=$androidMethod, isAcApp=$isAcApp"
echo "packageMethod=$packageMethod, branch=$branch"

# 应用包桌面路径
apkPath=""

# 检测入参
function parameterCheck() {
    if [[ $(pwd) =~ '/script' ]]; then
        cd ../
    fi

    platform=$(echo $platform | tr '[:upper:]' '[:lower:]')
    appType=$(echo $appType | tr '[:upper:]' '[:lower:]')
    [[ -z $platform ]] && platform="android"
    [[ -z $env ]] && env="dev"
    [[ -z $appType ]] && appType="ac"

    if [[ $appType =~ 'ac' ]]; then
        appType="app_ac"
        showAppType="ac"
    else
        appType="app_im"
        showAppType="im"
    fi

    [[ -z $version ]] && version="1.0.1"
    [[ -z $buildCode ]] && buildCode="10"

    local defaultFileName="${appName}.${version}(${buildCode})_${showAppType}_${env}_${cur_date}"
    [[ -n $fileName ]] && defaultFileName=$fileName

    local androidFileName="${defaultFileName}.apk"
    [[ $androidMethod == '3' ]] && androidFileName="${defaultFileName}.aab"

    apkPath="$HOME/Desktop/${androidFileName}"

    echo "待打包平台: Android env=$env, appType=$appType"
    echo "版本: $version($buildCode)"
    echo "Android包桌面路径：$apkPath"
    echo "****************** 检测入参完成 ******************"
}

function modifyCode() {
  local configPath="app/src/main/java/com/app/h5/config/ShellConfig.java"

  # 参数设置
  local sysId="${1:-1}"
  local groupId="${2:-76}"
  local agentId="${3:-}"
  local appType="${4:-app_ac}"
  local appNameCn="${5:-18bet}"
  local appNameEn="${6:-18bet}"
  local openInnerTools="${7:-false}"
  local isAcApp="${8:-true}"

  # 打印输入参数（调试用）
  echo "====== 调试信息 ======"
  echo "配置文件路径: $configPath"
  echo "接收到的参数:"
  echo "sysId=$sysId | groupId=$groupId | agentId=$agentId"
  echo "appType=$appType | appNameCn=$appNameCn | appNameEn=$appNameEn"
  echo "openInnerTools=$openInnerTools | isAcApp=$isAcApp"
  echo "当前系统类型: $OSTYPE"
  echo "====================="

  # 检查文件是否存在
  if [[ ! -f "$configPath" ]]; then
    echo "错误：配置文件不存在 $configPath"
    return 1
  fi

  # 备份原文件
  echo "正在备份原文件..."
  cp -v "$configPath" "${configPath}.bak" || {
    echo "错误：文件备份失败"
    return 1
  }

  # 打印修改前的关键行（调试用）
  echo "修改前内容:"
  grep -E 'public final (String|boolean)' "$configPath"
  echo "---------------------"

  # macOS/Linux 兼容的 sed 语法
  echo "正在修改配置文件..."
  if [[ "$OSTYPE" == "darwin"* ]]; then
    sed -i '' "
      s/public final String sysId = .*/public final String sysId = \"$sysId\";/
      s/public final String groupId = .*/public final String groupId = \"$groupId\";/
      s/public final String agentId = .*/public final String agentId = \"$agentId\";/
      s/public final String appTypeEnum = .*/public final String appTypeEnum = \"$appType\";/
      s/public final String appNameCn = .*/public final String appNameCn = \"$appNameCn\";/
      s/public final String appNameEn = .*/public final String appNameEn = \"$appNameEn\";/
      s/public final boolean openInnerTools = .*/public final boolean openInnerTools = $openInnerTools;/
    " "$configPath"
  else
    sed -i "
      s/public final String sysId = .*/public final String sysId = \"$sysId\";/
      s/public final String groupId = .*/public final String groupId = \"$groupId\";/
      s/public final String agentId = .*/public final String agentId = \"$agentId\";/
      s/public final String appTypeEnum = .*/public final String appTypeEnum = \"$appType\";/
      s/public final String appNameCn = .*/public final String appNameCn = \"$appNameCn\";/
      s/public final String appNameEn = .*/public final String appNameEn = \"$appNameEn\";/
      s/public final boolean openInnerTools = .*/public final boolean openInnerTools = $openInnerTools;/
    " "$configPath"
  fi

  # 打印修改后的关键行（调试用）
  echo "修改后内容:"
  grep -E 'public final (String|boolean)' "$configPath"
  echo "---------------------"

  # 验证修改
  if grep -q "appNameCn = \"$appNameCn\"" "$configPath"; then
    echo "✅ Java配置修改成功"
    return 0
  else
    echo "❌ 错误：配置修改未生效，正在恢复备份..."
    mv -v "${configPath}.bak" "$configPath"
    return 1
  fi
}


# 主流程
parameterCheck
modifyAndroidVersion $version $buildCode
[[ $isShellApp == false ]] && modifyAppName "$appNameEn" "$appNameCn" "$packageRes"
modifyCode
package_android $androidMethod "$apkPath"

echo "****************** Android打包耗时: ${SECONDS}秒 ******************"
